package grpcserveruser

import (
	"context"
	"errors"
	"go-gin-api/app/model/user"
	grpcuser "go-gin-api/app/proto/user"
)

type UserServer struct {
	user user.UserRepository
}

func NewUserSever(user user.UserRepository) grpcuser.UserHandler {
	return &UserServer{
		user: user,
	}
}

// 用户新增 User
func (s *UserServer) User(ctx context.Context, req *grpcuser.UserRequest, res *grpcuser.UserResponse) error {
	flag := s.user.ExistsUserByName(req.Username, 0)
	if flag {
		return errors.New("user name 存在 不允许添加")
	}
	err := s.user.UserAdd(req)
	if err == nil {
		res.Res = true
	}
	return err
}

// 用户删除 UserDel
func (s *UserServer) UserDel(ctx context.Context, req *grpcuser.UserDelRequest, res *grpcuser.UserDelResponse) error {
	err := s.user.UserDel(req)
	if err == nil {
		res.Res = true
	}
	return err
}

// 用户修改 UserUpdate
func (s *UserServer) UserUpdate(ctx context.Context, req *grpcuser.UserUpdateRequest, res *grpcuser.UserUpdateResponse) error {
	flag := s.user.ExistsUserByName(req.Username, int(req.Id))
	if flag {
		return errors.New("user name 存在 不允许添加")
	}
	err := s.user.UserUpdate(req)
	if err == nil {
		res.Res = true
	}
	return err
}

// 用户列表 UserList
func (s *UserServer) UserList(ctx context.Context, req *grpcuser.UserListRequest, res *grpcuser.UserListResponse) error {
	var (
		userList []*grpcuser.UserInfoResponse
	)
	data, err := s.user.UserList(req)
	if err != nil {
		return errors.New("user 获取失败")
	}
	if len(data) > 0 {
		for _, item := range data {
			row := &grpcuser.UserInfoResponse{
				Id:        int32(item.ID),
				Username:      item.Username,
				Mobile:      int32(item.Mobile),
				Status:    int32(item.Status),
				CreatedAt: item.CreatedAt.Format("2006-01-02 15:04:05"),
			}
			userList = append(userList, row)
		}
	}
	res.List = userList
	return nil
}

// 用户详情 UserInfo
func (s *UserServer) UserInfo(ctx context.Context, req *grpcuser.UserInfoRequest, res *grpcuser.UserInfoResponse) error {
	data, err := s.user.UserInfo(req)
	if err != nil {
		return errors.New("user 获取失败")
	}
	res.Username = data.Username
	res.Mobile = int32(data.Mobile)
	res.Status = int32(data.Status)
	res.CreatedAt = data.CreatedAt.Format("2006-01-02 15:04:05")
	res.Id = int32(data.ID)
	return nil
}
